/* eslint-disable no-tabs */
import qs from 'querystring'
import { getCurWebsite } from '@/views/common'
import { http } from '@/utils/axios'

export const scriptText = `
  <script>
  const style = document.createElement('style');
  style.innerText = 'a{color:#333}table{width:100%;background-color:#f2f2f2;border-collapse:collapse}thead tr th{background-color:#7a7a7a;padding:10px 4px;color:#fff}table,table tr th,table tr td{border:1px solid #999}.thead-row2 th{background-color:#ffe18a;color:#626262}tr{border-bottom:1px solid #999}tr td{background-color:#f2f2f2;padding:10px 4px;color:#333;text-align:right;min-width:70px}a:-webkit-any-link{text-decoration:none}'
  document.querySelector('head').appendChild(style)
  </script>
`

export default {
  methods: {
    _getBabaItem (item) {
      return new Promise((resolve, reject) => {
        // eslint-disable-next-line no-unused-vars
        const { name, psw, code, level } = item
        console.log(item)
        const children = this.getChilren(item.children)
        // eslint-disable-next-line no-unused-vars
        const { startDate, endDate } = this
        const data = qs.stringify({
          // username: name || 'SMWSub111',
          // pwd: psw || '111333aa@',
          // date_start: startDate || '10/06/2021',
          // date_end: endDate || '10/06/2021'
          // children: JSON.stringify([{ name: 'SMWA1' }])
          username: name,
          pwd: psw,
          date_start: startDate,
          date_end: endDate,
          children: children && children.length ? JSON.stringify(children) : ''
        })

        const babaUrl = getCurWebsite() + '/baba/gen'

        http({
          method: 'post',
          url: babaUrl,
          withCredentials: false,
          data
        }).then(res => {
          console.log(res)
          // if (res.data) {
          //   resolve(res.data)
          // } else {
          if (this.checkSuccess(res)) {
            resolve(res.data.data)
          } else {
            reject((res && res.data && res.data.message) || '')
          }
        }).catch(e => {
          console.log('get item baba data error: ')
          console.error(e)
          reject(e)
        })
      })
    },
    async getBabaAllData (reGetList) {
      const list = reGetList || this.accountList
      if (!list || !list.length) return

      this.loading = true
      let { name } = list[0]
      const { startDate, endDate } = this
      if (startDate && endDate) {
        name = startDate.substring(5) + '-' + endDate.substring(5) + '——' + name
      }

      const callback = () => {
        if (this.waitExportList.length === 0) {
          return this.$message.info('请求数据为空')
        }
        const result = this.waitExportList.map(obj => {
          return `
              <h3>${obj.name}</h3>
              ${obj.data}
            `
        })
        const tplData = result.join('')
        this.sendToMainProcess(name + '.html', tplData + scriptText)
      }
      // const resultList = []
      let tempList = []
      const len = list.length
      let index = 0
      for (let i = 0; i < len; i++) {
        const item = list[i]
        const itemIndex = this.accountList.findIndex(a => a.name === item.name)
        this.$set(this.accountList[itemIndex], 'statusText', '请求中...')
        this._getBabaItem(item)
          .then(r => {
            this.$set(this.accountList[itemIndex], 'statusText', '请求成功')
            // resultList.push(...r)
            tempList[i] = [...r]
          })
          .catch(e => {
            this.errorList.push(item)
            this.$set(this.accountList[itemIndex], 'statusText', typeof e === 'string' ? e : '请求失败...')
          })
          .finally(() => {
            index = index + 1
            if (index === len) {
              console.log(tempList)
              tempList = tempList.filter(e => e)
              tempList.forEach(item => {
                // resultList.push(...item)
                this.waitExportList.push(...item)
              })
              this.loading = false
              this.checkExistErrorList(() => callback())
              // callback()
            }
          })
      }
    },
    async getBabaItemData (item, i) {
      try {
        this.$set(this.accountList[i], 'statusText', '请求中...')
        this.loading = true
        let { name } = item
        const { startDate, endDate } = this
        const data = await this._getBabaItem(item)
        let result = ''
        data.forEach(obj => {
          result += `
            <h3>${obj.name}</h3>
            ${obj.data}
          `
        })
        console.log(data)
        if (startDate && endDate) {
          name = startDate.substring(5) + '-' + endDate.substring(5) + '——' + name
        }
        this.$set(this.accountList[i], 'statusText', '请求成功')
        const tplData = result
        this.sendToMainProcess(name + '.html', tplData + scriptText)
      } catch (e) {
        this.$set(this.accountList[i], 'statusText', e || '请求失败...')
      } finally {
        this.loading = false
      }
    }
  }
}
